const path=require('path');

// 用于把生成的js文件插入到index.html中；
const HtmlWebpackPlugin = require('html-webpack-plugin');

// 代码压缩
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');

// 构建前清理目录
const CleanWebpackPlugin = require('clean-webpack-plugin');



var config = {
	entry: path.join(__dirname, 'src/index.js'),

	/*输出到dist文件夹，输出文件名字为bundle.js*/
	output: {
		path: path.join(__dirname, './dist'),
		filename: 'bundle.js'
	},
	devServer: {
		//contentBase: path.join(__dirname, './dist')
	//	publicPath: '../assets/',
        filename:'bundle.js'
	},

	resolve: {
		// 为路起一个别名，方便直接应用路径
		alias: {
			pages: path.join(__dirname, 'src/pages'),
			img: path.join(__dirname, 'src/img'),

		}
	},

	module: {
		rules: [
			{
				// 插件的顺序是先转换在检查
				test: /\.js$/,
				use: ['babel-loader'],
				include: path.join(__dirname, 'src')
			},
			{
				test: /\.css$/,
				use: ['style-loader', 'css-loader']
			},
			{
				test: /\.(png|jpg|gif|mp4)$/,
				use: [{
					loader: 'url-loader',
					options: {
						limit: 8192,
						name:'img/[name].[ext]'
					}
				}]
			}
		]
	},

};



// webpack 版本是4.19，安装官网的说明，这个文件应该导出一个函数。
module.exports = (env, argv) => {

	if (argv.mode === 'development') {
		config.devtool = 'source-map';
		config.plugins= [
			new HtmlWebpackPlugin({
				filename: 'index.html',
				template: path.join(__dirname, 'index.html')
			}),
			new UglifyJSPlugin()
		];
	}

	if (argv.mode === 'production') {
		config.plugins= [
			new CleanWebpackPlugin(['dist']),
			new HtmlWebpackPlugin({
				filename: 'index.html',
				template: path.join(__dirname, 'index.html')
			}),
			new UglifyJSPlugin()
		];
	}

	return config;
};
